<template>
  <q-page class="q-pa-md">

    <!--    fill-input  -->
    <q-form @submit.prevent="addQuery">

      <q-select
        v-if="showSelectslinename"
        v-model="queryInputlinename"
        :options="filteredOptionslinename"
        label="线路名称"
        use-input

        input-debounce="500"
        @filter="filterOptionslinename"
        dense
        filled
        class="q-mb-md"
      >
        <template v-slot:no-option>
          <q-item>
            <q-item-section class="text-grey">
              无匹配内容
            </q-item-section>
          </q-item>
        </template>
      </q-select>


      <q-select
        v-if="showSelectsoperatemission"
        v-model="queryInputoperatemission"
        :options="filteredOptionsoperatemission"
        label="操作任务"
        use-input

        input-debounce="500"
        @filter="filterOptionsoperatemission"
        dense
        filled
        class="q-mb-md"
      >
        <template v-slot:no-option>
          <q-item>
            <q-item-section class="text-grey">
              无匹配内容
            </q-item-section>
          </q-item>
        </template>
      </q-select>




      <q-checkbox v-model="showSelects1" label="逐项令-综合令" class="q-mb-md"></q-checkbox>


      <q-checkbox v-model="showSelects" label="最大负荷" class="q-mb-md"></q-checkbox>

      <q-checkbox v-model="showSelects2" label="预案" class="q-mb-md"></q-checkbox>
      <q-checkbox v-model="showSelects3" label="定值单" class="q-mb-md"></q-checkbox>
      <!----------------------------- 最大负荷 ------------------------->
      <q-select
        v-if="showSelects"
        v-model="queryInput"
        :options="filteredOptions"
        label="最大负荷"
        use-input

        input-debounce="500"
        @filter="filterOptions"
        dense
        filled
        class="q-mb-md"
      >
        <template v-slot:no-option>
          <q-item>
            <q-item-section class="text-grey">
              无匹配内容
            </q-item-section>
          </q-item>
        </template>
      </q-select>


      <!--------------------------------- 操作票的推荐 ---------------------------------->

      <q-select
        v-if="showSelects1"
        v-model="queryInputsysunitname"
        :options="filteredOptionssysunitname"
        label="单位（逐项令）"
        use-input

        input-debounce="500"
        @filter="filterOptionssysunitname"
        dense
        filled
        class="q-mb-md"
      >
        <template v-slot:no-option>
          <q-item>
            <q-item-section class="text-grey">
              无匹配内容
            </q-item-section>
          </q-item>
        </template>
      </q-select>


      <q-select
        v-if="showSelects1"
        v-model="queryInputsyscontent"
        :options="filteredOptionssyscontent"
        label="操作项目（逐项令）"
        use-input

        input-debounce="500"
        @filter="filterOptionssyscontent"
        dense
        filled
        class="q-mb-md"
      >
        <template v-slot:no-option>
          <q-item>
            <q-item-section class="text-grey">
              无匹配内容
            </q-item-section>
          </q-item>
        </template>
      </q-select>


      <q-select
        v-if="showSelects1"
        v-model="queryInputcomunitname"
        :options="filteredOptionscomunitname"
        label="单位（综合令）"
        use-input

        input-debounce="500"
        @filter="filterOptionscomunitname"
        dense
        filled
        class="q-mb-md"
      >
        <template v-slot:no-option>
          <q-item>
            <q-item-section class="text-grey">
              无匹配内容
            </q-item-section>
          </q-item>
        </template>
      </q-select>


      <q-select
        v-if="showSelects1"
        v-model="queryInputcomcontent"
        :options="filteredOptionscomcontent"
        label="操作项目（综合令）"
        use-input

        input-debounce="500"
        @filter="filterOptionscomcontent"
        dense
        filled
        class="q-mb-md"
      >
        <template v-slot:no-option>
          <q-item>
            <q-item-section class="text-grey">
              无匹配内容
            </q-item-section>
          </q-item>
        </template>
      </q-select>

      <q-select
        v-if="showSelects1"
        v-model="queryInputcomps"
        :options="filteredOptionscomps"
        label="备注"
        use-input

        input-debounce="500"
        @filter="filterOptionscomps"
        dense
        filled
        class="q-mb-md"
      >
        <template v-slot:no-option>
          <q-item>
            <q-item-section class="text-grey">
              无匹配内容
            </q-item-section>
          </q-item>
        </template>
      </q-select>

      <!--  -------------------------------------    预案推荐 ---------------------------------- -->






      <q-select
        v-if="showSelects2"
        v-model="queryInputnamedetail"
        :options="filteredOptionsnamedetail"
        label="预案操作"
        use-input

        input-debounce="500"
        @filter="filterOptionsnamedetail"
        dense
        filled
        class="q-mb-md"
      >
        <template v-slot:no-option>
          <q-item>
            <q-item-section class="text-grey">
              无匹配内容
            </q-item-section>
          </q-item>
        </template>
      </q-select>




      <!-----------------------------定值单----------------------------------->

      <q-select
        v-if="showSelects3"
        v-model="queryInputcodename"
        :options="filteredOptionscodename"
        label="控制字名称"
        use-input

        input-debounce="500"
        @filter="filterOptionscodename"
        dense
        filled
        class="q-mb-md"
      >
        <template v-slot:no-option>
          <q-item>
            <q-item-section class="text-grey">
              无匹配内容
            </q-item-section>
          </q-item>
        </template>
      </q-select>


      <q-select
        v-if="showSelects3"
        v-model="queryInputcodevalue"
        :options="filteredOptionscodevalue"
        label="控制字值"
        use-input

        input-debounce="500"
        @filter="filterOptionscodevalue"
        dense
        filled
        class="q-mb-md"
      >
        <template v-slot:no-option>
          <q-item>
            <q-item-section class="text-grey">
              无匹配内容
            </q-item-section>
          </q-item>
        </template>
      </q-select>
      <!--select * from line left join operate on line.linename = operate.operatelinename where line.linename = queryInput-->


      <!--      <q-select-->
      <!--        v-model="queryInput3"-->
      <!--        :options="filteredOptions2"-->
      <!--        label="operatemission"-->
      <!--        use-input-->

      <!--        input-debounce="500"-->
      <!--        @filter="filterOptions2"-->
      <!--        dense-->
      <!--        filled-->
      <!--        class="q-mb-md"-->
      <!--      >-->
      <!--        <template v-slot:no-option>-->
      <!--          <q-item>-->
      <!--            <q-item-section class="text-grey">-->
      <!--              无匹配内容-->
      <!--            </q-item-section>-->
      <!--          </q-item>-->
      <!--        </template>-->
      <!--      </q-select>-->




      <q-btn type="submit" label="查询" color="primary" class="q-ml-md"
             v-if="showSelects || showSelects1 || showSelects2 || showSelects3"
      />
    </q-form>


<!--    <div v-if="queries.length">-->
<!--      <h3>查询内容</h3>-->
<!--      <div>-->
<!--        <q-chip-->
<!--          v-for="(query, index) in queries"-->
<!--          :key="index"-->
<!--          removable-->
<!--          @remove="removeQuery(index)"-->
<!--          class="q-mr-md q-mb-md"-->
<!--        >-->
<!--          {{ query }}-->
<!--        </q-chip>-->
<!--      </div>-->
<!--    </div>-->

<!--    &lt;!&ndash;   加入组件&ndash;&gt;-->

<!--    &lt;!&ndash; 搜索组件显示 &ndash;&gt;-->
<!--    <div class="q-pa-md">-->
<!--      <div class="q-pa-md row q-gutter-x-md">-->
<!--        <div class="col">-->
<!--          <q-select-->
<!--            v-model="selectedColumns"-->
<!--            multiple-->
<!--            :options=columns-->
<!--            label="选择要显示的列"-->
<!--          />-->
<!--        </div>-->
<!--        <div class="col">-->
<!--          <q-input dense filled v-model="searchQuery" label="输入搜索内容..."></q-input>-->
<!--        </div>-->
<!--        <div class="col-auto">-->

<!--          <q-btn dense rounded color="primary" icon="search" label="搜索" @click="searchData"></q-btn>-->
<!--        </div>-->
<!--      </div>-->
<!--      <q-btn label="Export to Excel" color="primary" @click="exportToExcel" />-->

<!--      <q-table :data="querySearchResult" :columns="filteredColumns" flat binary-state-sort class="q-mt-md"></q-table>-->

<!--    </div>-->

<!--    &lt;!&ndash;    加入组件结束&ndash;&gt;-->

    <div v-if="sqlgenPro">
      <h3>        </h3>
      <p>{{ this.result }}</p>
    </div>
  </q-page>
</template>

<script>
import * as XLSX from 'xlsx';
import axios from 'axios';
export default {
  data() {
    return {
      selectString:'',

      // '66千伏平凤二线送电','66千伏平凤二线停电'
      ywNamesoperatemission:['送电','停电'],
      showSelectsoperatemission:true,
      queryInputoperatemission:'',
      filteredOptionsoperatemission:'',

      //

      showSelectslinename:true,
      queryInputlinename:'',
      filteredOptionslinename:[],
      ywNameslinename:['平钢一线','平钢二线','平凤一线','平凤二线','双河一线','双河二线','平工一线','平工二线','平铝二线','平铝五线','友平一线'],


      // 推荐生成
      sqlgenPro: false,

      //
      queryString: '',
      showSelects3: false,

      showSelects1: false,

      showSelects2: false,
      // 预案
      ywNamescomps: '',
      ywNamesnamedetail: '',
      ywNamescodename: '',
      ywNamescodevalue: '',


      queryInputcomps: '',
      queryInputnamedetail: '',
      queryInputcodename: '',
      queryInputcodevalue: '',

      filteredOptionscomps: [],
      filteredOptionsnamedetail: [],
      filteredOptionscodename: [],
      filteredOptionscodevalue: [],

      // 操作票


      ywNamessysunitname: '',
      ywNamessyscontent: '',
      ywNamescomunitname: '',
      ywNamescomcontent: '',


      queryInputsysunitname: '',
      queryInputsyscontent: '',
      queryInputcomunitname: '',
      queryInputcomcontent: '',

      filteredOptionssysunitname: [],
      filteredOptionssyscontent: [],
      filteredOptionscomunitname: [],
      filteredOptionscomcontent: [],


      // 》》》》》》》》》》》》
      searchQuery: '',
      columns2: [],
      selectedColumns2: [], // 用户选择显示的列名数组
      filteredOptions2: [],  // 过滤后的选项
      ywNames2: '',
      queryInput2: '',
      queries2: [],
      result2: '',
      querySearchResult2: [],

      columns: [],
      showSelects: false, // 控制 q-select 显示的状态
      selectedColumns: [], // 用户选择显示的列名数组
      filteredOptions: [],  // 过滤后的选项
      ywNames: ['32.36'],
      queryInput: '',
      queries: [],
      result: '',
      querySearchResult: [],
    };
  },
  watch: {
    // 监听 queryInputlinename

    async queryInputlinename(newVal, oldVal) {
      console.log(`数据从 ${oldVal} 变更为 ${newVal}`);


    }
    ,

    // 监控 'dataValue' 数据属性
    async queryInputoperatemission(newVal, oldVal) {
      console.log(`数据从 ${oldVal} 变更为 ${newVal}`);

      // if (newVal === '送电') {

//
      localStorage.setItem('operatemission',newVal)
        let selectString = localStorage.getItem('sqlselect')  //.slice(0, -1)
        let queryString = localStorage.getItem('sqlwhere')
        let groupBy = 'syscontent'
        var sqlgroup = "select " + groupBy + " from sqlgen where linename = '"+this.queryInputlinename+"' and syscontent like '%"+newVal+"%'  group by " + groupBy
        let response = await axios.post(
          'http://43.136.220.136:9002/_sql?format=json',
          {
            "query": sqlgroup
          },
          {
            headers: {
              'Content-Type': 'application/json',
              'Authorization': 'Basic ' + btoa('admin:1992A1573')
            }
          }
        );
        console.log(response);
// 处理响应数据
        var results = response.data.rows;  // 从SQL查询结果获取rows
// 将查询结果中的namedetail字段值取出来组成一个数组
        this.ywNamessyscontent = results


        // this.ywNamessyscontent = ['汇报66千伏平凤二线有关作业全结束，现场安全措施全拆除，人员全撤离，送电无问题。', '汇报66千伏平凤二线及66千伏2号主变有关作业全结束，现场安全措施全拆除，人员全撤离，送电无问题。', '拆除66千伏平凤二线10912线路侧地线。', '拆除66千伏平凤二线4952线路侧地线。', '合上66千伏平凤二线49522刀闸。', '合上66千伏平凤二线49526刀闸。', '合上66千伏平凤二线4952开关。', '66千伏平凤二线10912开关及66千伏2号主变由检修转运行。', '66千伏1号主变由运行转热备用。', '投入主变互投装置。']
        // this.ywNamessyscontent=['汇报66千伏平凤二线有关作业全结束，现场安全措施全拆除，人员全撤离，送电无问题。','汇报66千伏平凤二线及66千伏2号主变有关作业全结束，现场安全措施全拆除，人员全撤离，送电无问题。','拆除66千伏平凤二线10912线路侧地线。','拆除66千伏平凤二线4952线路侧地线。','合上66千伏平凤二线49522刀闸。','合上66千伏平凤二线49526刀闸。','合上66千伏平凤二线4952开关。','66千伏平凤二线10912开关及66千伏2号主变由检修转运行。','66千伏1号主变由运行转热备用。','投入主变互投装置。']

      //
      // } else {
      //   this.ywNamessyscontent = ['退出主变备自投装置。', '66千伏1号主变由热备用转运行。', '66千伏2号主变由运行转检修。', '拉开66千伏平凤二线4952开关。', '拉开66千伏平凤二线49526刀闸。', '拉开66千伏平凤二线49522刀闸。', '在66千伏平凤二线4952线路侧装设一组地线。', '在66千伏平凤二线10912线路侧装设一组地线。', '通知66千伏平凤二线及2号主变已停电，所内有关作业可以开始，现场安全措施自行负责。', '通知67千伏平凤二线线路已停电，线路有关作业可以开始，现场安全措施自行负责。']
      //
      // }

      // 在这里可以执行任何响应数据变化的操作
    }
  },
  computed: {
    filteredColumns() {
      return this.selectedColumns;
    },

  },
  methods: {
    searchData() {
    },

    filterOptionsoperatemission(val, update) {
      update(() => {
        if (val) {
          const filter = new RegExp(val, 'i')
          this.filteredOptionsoperatemission = this.ywNamesoperatemission.filter(v => v.match(filter))
        } else {
          this.filteredOptionsoperatemission = this.ywNamesoperatemission
        }
      });
    },
    // 预案
    filterOptionscomps(val, update) {
      update(() => {
        if (val) {
          const filter = new RegExp(val, 'i')
          this.filteredOptionscomps = this.ywNamescomps.filter(v => v.match(filter))
        } else {
          this.filteredOptionscomps = this.ywNamescomps
        }
      });
    },


    filterOptionslinename(val, update) {
      update(() => {
        if (val) {
          const filter = new RegExp(val, 'i')
          this.filteredOptionslinename = this.ywNameslinename.filter(v => v.match(filter))
        } else {
          this.filteredOptionslinename = this.ywNameslinename
        }
      });
    },


    filterOptionsnamedetail(val, update) {
      update(() => {
        if (val) {
          const filter = new RegExp(val, 'i')
          this.filteredOptionsnamedetail = this.ywNamesnamedetail.filter(v => v.match(filter))
        } else {
          this.filteredOptionsnamedetail = this.ywNamesnamedetail
        }
      });
    },

    filterOptionscodename(val, update) {
      update(() => {
        if (val) {
          const filter = new RegExp(val, 'i')
          this.filteredOptionscodename = this.ywNamescodename.filter(v => v.match(filter))
        } else {
          this.filteredOptionscodename = this.ywNamescodename
        }
      });
    },

    filterOptionscodevalue(val, update) {
      update(() => {
        if (val) {
          const filter = new RegExp(val, 'i')
          this.filteredOptionscodevalue = this.ywNamescodevalue.filter(v => v.match(filter))
        } else {
          this.filteredOptionscodevalue = this.ywNamescodevalue
        }
      });
    },

    //操作票
    filterOptionssysunitname(val, update) {
      update(() => {
        if (val) {
          const filter = new RegExp(val, 'i')
          this.filteredOptionssysunitname = this.ywNamessysunitname.filter(v => v.match(filter))
        } else {
          this.filteredOptionssysunitname = this.ywNamessysunitname
        }
      });
    },
    filterOptionssyscontent(val, update) {
      update(() => {
        if (val) {
          const filter = new RegExp(val, 'i')
          this.filteredOptionssyscontent = this.ywNamessyscontent.filter(v => v.match(filter))
        } else {
          this.filteredOptionssyscontent = this.ywNamessyscontent
        }
      });
    },
    filterOptionscomunitname(val, update) {
      update(() => {
        if (val) {
          const filter = new RegExp(val, 'i')
          this.filteredOptionscomunitname = this.ywNamescomunitname.filter(v => v.match(filter))
        } else {
          this.filteredOptionscomunitname = this.ywNamescomunitname
        }
      });
    },
    filterOptionscomcontent(val, update) {
      update(() => {
        if (val) {
          const filter = new RegExp(val, 'i')
          this.filteredOptionscomcontent = this.ywNamescomcontent.filter(v => v.match(filter))
        } else {
          this.filteredOptionscomcontent = this.ywNamescomcontent
        }
      });
    },

    // 》》》》》》》》》


    filterOptions(val, update) {
      update(() => {
        if (val) {
          const filter = new RegExp(val, 'i')
          this.filteredOptions = this.ywNames.filter(v => v.match(filter))
        } else {
          this.filteredOptions = this.ywNames
        }
      });
    },
    filterOptions2(val, update) {
      update(() => {
        if (val) {
          const filter = new RegExp(val, 'i')
          this.filteredOptions2 = this.ywNames2.filter(v => v.match(filter))
        } else {
          this.filteredOptions2 = this.ywNames2
        }
      });
    },
    addQuery() {
      this.search();
      // if (this.queryInput) {
      //   this.queries.push(this.queryInput);
      //
      //   this.search();
      //   // this.queryInput = '';
      // }
    },
    removeQuery(index) {

      this.queries.splice(index, 1);
      this.search();
    },
    searchQuery_native() {
      console.log("------------------")
    },
    buildElasticsearchQuery(queryInputlinename,queryInputoperatemission,queryInput, operatemission, sysunitname, syscontent, comunitname, comcontent, comps, namedetail, codename, codevalue) {
      const mustClauses = [];
      var queryString = ''
      var selectString = ''
      // 始终检查'linename'字段
      if (queryInputlinename) {
        mustClauses.push({
          "match_phrase": {
            "linename": queryInputlinename
          }
        });


        queryString = queryString + "linename" + " = '" + queryInputlinename + "' and "
        selectString = selectString + "linename,"

      }


      // if (queryInputoperatemission) {
      //   mustClauses.push({
      //     "match_phrase": {
      //       "operatemission": queryInputoperatemission
      //     }
      //   });
      //
      //
      //   queryString = queryString + "operatemission" + " = '" + queryInputoperatemission + "' and "
      //   selectString = selectString + "operatemission,"
      // }


      if (queryInput) {
        mustClauses.push({
          "match_phrase": {
            "maxload": queryInput
          }
        });

        queryString = queryString + "maxload" + " = '" + queryInput + "' and "
        selectString = selectString + "maxload,"
      }


      // 如果operatemission有值，也检查'description'字段
      if (operatemission) {
        mustClauses.push({
          "match_phrase": {
            "operatemission": operatemission
          }
        });

        queryString = queryString + " operatemission" + " = '" + operatemission + "' and "
        selectString = selectString + "operatemission,"

      }

      // 操作票


      if (sysunitname) {
        mustClauses.push({
          "match_phrase": {
            "sysunitname": sysunitname
          }
        });

        queryString = queryString + " sysunitname" + " = '" + sysunitname + "' and "
        selectString = selectString + "sysunitname,"

      }

      if (syscontent) {
        mustClauses.push({
          "match_phrase": {
            "syscontent": syscontent
          }
        });


        queryString = queryString + " syscontent" + " = '" + syscontent + "' and "
        selectString = selectString + "syscontent,"

      }

      if (comunitname) {
        mustClauses.push({
          "match_phrase": {
            "comunitname": comunitname
          }
        });

        queryString = queryString + " comunitname" + " = '" + comunitname + "' and "
        selectString = selectString + "comunitname,"
      }

      if (comcontent) {
        mustClauses.push({
          "match_phrase": {
            "comcontent": comcontent
          }
        });


        queryString = queryString + " comcontent" + " = '" + comcontent + "' and "
        selectString = selectString + "comcontent,"
      }

// 预案
      if (comps) {
        mustClauses.push({
          "match_phrase": {
            "comps": comps
          }
        });

        queryString = queryString + " comps" + " = '" + comps + "' and "
        selectString = selectString + "comps,"

      }

      if (namedetail) {
        mustClauses.push({
          "match_phrase": {
            "namedetail": namedetail
          }
        });

        queryString = queryString + " namedetail" + " = '" + namedetail + "' and "
        selectString = selectString + "namedetail,"

      }

      if (codename) {
        mustClauses.push({
          "match_phrase": {
            "codename": codename
          }
        });

        queryString = queryString + " codename" + " = '" + codename + "' and "
        selectString = selectString + "codename,"

      }

      if (codevalue.toString()) {
        mustClauses.push({
          "match_phrase": {
            "codevalue": codevalue.toString()
          }
        });

        queryString = queryString + " codevalue" + " = '" + codevalue + "' and "
        selectString = selectString + "codevalue,"

      }
      this.selectString = selectString
      this.queryString = queryString




      // 构建查询JSON
      var query = {
        "query": {
          "bool": {
            "must": mustClauses
          }
        }
      };
      localStorage.setItem("querygen",JSON.stringify(query))
      query.size = 10 // 根据你期望的最大文档数量调整


      return query;
    },

    exportToExcel() {
      const data = this.querySearchResult.map(row => {
        const rowData = {};
        this.filteredColumns.forEach(column => {
          rowData[column.label] = row[column.field];
        });
        return rowData;
      });

      const ws = XLSX.utils.json_to_sheet(data);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "Results");
      XLSX.writeFile(wb, "export.xlsx");
    },
    async search() {

      localStorage.setItem('caozuopiao',this.queryInputoperatemission)

      localStorage.setItem('xianlu',this.queryInputlinename)

      // queryInput
      localStorage.setItem('fuhe',this.queryInput)
      console.log("========search=======")
      var queryString = this.buildElasticsearchQuery(this.queryInputlinename,this.queryInputoperatemission,this.queryInput, this.queryInput2, this.queryInputsysunitname, this.queryInputsyscontent, this.queryInputcomunitname, this.queryInputcomcontent, this.queryInputcomps, this.queryInputnamedetail, this.queryInputcodename, this.queryInputcodevalue);
      console.log(queryString)
      localStorage.setItem('queryInputcodevalue',this.queryInputcodevalue)
      console.log(this.selectString)
      console.log(this.queryString + " 1=1")

      var sqlgen = "select "+ this.selectString.slice(0, -1) +" from sqlgen where " + this.queryString + " 1=1 limit 10"

      localStorage.setItem('sqlselect',this.selectString)
      localStorage.setItem('sqlwhere',this.queryString+ " 1=1 ")
      console.log(sqlgen)
      localStorage.setItem("sqlgen",sqlgen)
      this.sqlgenPro = sqlgen
      // 发送查询请求
      console.log("+++++++++++"+queryString)
      const response = await axios.post(
        'http://43.136.220.136:9002/sqlgen/_search'
        , queryString,
        {
          headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Basic ' + btoa('admin:1992A1573')
          }
        }
      );
      console.log("-----------------------")
      console.log(response)
      localStorage.setItem('shijian',response.data.hits.hits[0]._source.begindate)
      const sourceArray = response.data.hits.hits.map(item => item._source);

// 现在sourceArray包含了所有原始数组元素的_source字段
      console.log(sourceArray);
      localStorage.setItem('queryResult',JSON.stringify(sourceArray))

      this.searchResults = response.data.hits.hits.map(hit => hit._source);
      // 处理响应数据
      if (this.searchResults.length > 0) {
        this.columns = Object.keys(this.searchResults[0]).map(key => ({
          name: key,
          label: key, // 可以在这里将 key 转换为更友好的标签
          field: key,
          align: 'left',
          sortable: true
        }));
      }
      this.querySearchResult = this.searchResults

      // data.push({"key":hits[0].key+"-"+hits2[0].key,"value":hits[0].doc_count})

      //   try {
      //     // 发送 GET 请求并等待响应
      //     // 将条件传过去就ok了 当前输入数组内容作为参数传入。
      //     console.log(this.queries)
      //     const response = await axios.get('http://127.0.0.1:4444/get_xiangtongyongtu_names', {
      //     params: { items_yw: JSON.stringify(this.queries) }  // 确保键名与后端匹配
      //   });
      //     // 处理成功情况
      //
      //     console.log('Road names:', response.data.road_names);
      //     this.result = `当前查询结果: ${JSON.stringify({"所属光缆":response.data[0]['所属光缆'],"统计值":response.data[0]['数量']})}`;
      //     localStorage.setItem('渲染',JSON.stringify(response.data[0]))
      //
      //     return ;
      // } catch (error) {
      //     // 处理错误情况
      //     console.error('Error fetching data:', error);
      // }

      // console.log("search")
      // const uniqueItems = {};
      // const data = [];
      // var queriesq = []
      // console.log(this.queries)
      //
      // for (const query1 of this.queries) {
      //   queriesq = []
      //   queriesq.push(query1)
      //     console.log(query1)
      //     if (queriesq.length>0) {
      //     if (!queriesq.includes("SDH")) {
      //           queriesq.push("SDH");
      //         }
      //     // 构建查询条件
      //     const mustQueries = queriesq.map(condition => ({
      //       match_phrase: {
      //         "对应光路": condition
      //       }
      //     }));
      //
      //     // 构建最终查询
      //     const query = {
      //       bool: {
      //         must: mustQueries
      //       }
      //     };
      //
      //     try {
      //       // 发送查询请求
      //       const response = await axios.post(
      //         'http://43.136.220.136:9002/xianmen_guanglu/_search',
      //         {
      //           query: query,
      //          "size": 0,
      //           "aggs": {
      //             "by_belonging_cable": {
      //               "terms": {
      //                 "field": "所属光缆.keyword"
      //               },
      //               "aggs": {
      //                 "unique_routes": {
      //                   "cardinality": {
      //                     "field": "对应光路.keyword"
      //                   }
      //                 }
      //               }
      //             },
      //             "by_route": {
      //               "terms": {
      //                 "field": "对应光路.keyword"
      //               },
      //               "aggs": {
      //                 "unique_cables": {
      //                   "cardinality": {
      //                     "field": "所属光缆.keyword"
      //                   }
      //                 }
      //               }
      //             }
      //           }
      //         },
      //         {
      //           headers: {
      //             'Content-Type': 'application/json',
      //             'Authorization': 'Basic ' + btoa('admin:1992A1573')
      //           }
      //         }
      //       );
      //
      //       // 处理响应数据
      //       const hits = response.data.aggregations.by_belonging_cable.buckets;
      //       const hits2 = response.data.aggregations.by_route.buckets;
      //       const result = hits[0].key;
      //       data.push({"key":hits[0].key+"-"+hits2[0].key,"value":hits[0].doc_count})
      //
      //     } catch (error) {
      //       console.error("查询失败:", error);
      //       this.result = '查询失败';
      //     }
      //   } else {
      //     this.result = '暂无查询内容';
      //   }
      // }
      //
      // 停止3秒
      await new Promise(resolve => setTimeout(resolve, 3000));
      this.sqlgenPro = true
      this.result = `解析已完成`;

    }
  },
  async mounted() {

    // 发送查询请求
    var response = await axios.post(
      'http://43.136.220.136:9002/sqlgen/_search',
      {
        "size": 0,
        "aggs": {
          "unique_maxload": {
            "terms": {
              "field": "maxload",
              "size": 40000
            }
          }
        }
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Basic ' + btoa('admin:1992A1573')
        }
      }
    );
    console.log(response)
    // 处理响应数据
    var hits = response.data.aggregations.unique_maxload.buckets;
    // 将这里下边的所有json中的key取出来组成一个数组
    var keys = hits.map(hit => hit.key);
    // this.ywNames = keys
    console.log(keys)
    // ------------------------------------------------------------------------
    // data.push({"key":hits[0].key+"-"+hits2[0].key,"value":hits[0].doc_count})


    // linename推荐

    let selectString = localStorage.getItem('sqlselect')  //.slice(0, -1)
    let queryString = localStorage.getItem('sqlwhere')
    let groupBy = 'linename'
    var sqlgroup = "select "+ groupBy +" from sqlgen  group by " +groupBy

    response = await axios.post(
      'http://43.136.220.136:9002/_sql?format=json',
      {
        "query": sqlgroup
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Basic ' + btoa('admin:1992A1573')
        }
      }
    );
    console.log(response);
// 处理响应数据
    var results = response.data.rows;  // 从SQL查询结果获取rows
// 将查询结果中的namedetail字段值取出来组成一个数组
    this.ywNameslinename = results



    // 最大负荷推荐
    selectString = localStorage.getItem('sqlselect')  //.slice(0, -1)
    queryString = localStorage.getItem('sqlwhere')
    groupBy = 'maxload'
    sqlgroup = "select "+ groupBy +" from sqlgen  group by " +groupBy

    response = await axios.post(
      'http://43.136.220.136:9002/_sql?format=json',
      {
        "query": sqlgroup
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Basic ' + btoa('admin:1992A1573')
        }
      }
    );
    console.log(response);
// 处理响应数据
    var results = response.data.rows;  // 从SQL查询结果获取rows
// 将查询结果中的namedetail字段值取出来组成一个数组
    this.ywNames = results




    // ------------------------操作票推荐---------------------------------------















    // 发送查询请求
    response = await axios.post(
      'http://43.136.220.136:9002/sqlgen/_search',
      {
        "size": 0,
        "aggs": {
          "unique_sysunitname": {
            "terms": {
              "field": "sysunitname.keyword",
              "size": 40000
            }
          }
        }
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Basic ' + btoa('admin:1992A1573')
        }
      }
    );
    console.log(response)
    // 处理响应数据
    hits = response.data.aggregations.unique_sysunitname.buckets;
    // 将这里下边的所有json中的key取出来组成一个数组
    keys = hits.map(hit => hit.key);
    this.ywNamessysunitname = keys
    console.log(keys)


// 发送查询请求
    response = await axios.post(
      'http://43.136.220.136:9002/sqlgen/_search',
      {
        "size": 0,
        "aggs": {
          "unique_syscontent": {
            "terms": {
              "field": "syscontent.keyword",
              "size": 40000
            }
          }
        }
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Basic ' + btoa('admin:1992A1573')
        }
      }
    );
    console.log(response)
    // 处理响应数据
    hits = response.data.aggregations.unique_syscontent.buckets;
    // 将这里下边的所有json中的key取出来组成一个数组
    keys = hits.map(hit => hit.key);
    this.ywNamessyscontent = keys
    console.log(keys)


// 发送查询请求
    response = await axios.post(
      'http://43.136.220.136:9002/sqlgen/_search',
      {
        "size": 0,
        "aggs": {
          "unique_comunitname": {
            "terms": {
              "field": "comunitname.keyword",
              "size": 43000
            }
          }
        }
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Basic ' + btoa('admin:1992A1573')
        }
      }
    );
    console.log(response)
    // 处理响应数据
    hits = response.data.aggregations.unique_comunitname.buckets;
    // 将这里下边的所有json中的key取出来组成一个数组
    keys = hits.map(hit => hit.key);
    this.ywNamescomunitname = keys
    console.log(keys)


// 发送查询请求
    response = await axios.post(
      'http://43.136.220.136:9002/sqlgen/_search',
      {
        "size": 0,
        "aggs": {
          "unique_comcontent": {
            "terms": {
              "field": "comcontent.keyword",
              "size": 40000
            }
          }
        }
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Basic ' + btoa('admin:1992A1573')
        }
      }
    );
    console.log(response)
    // 处理响应数据
    hits = response.data.aggregations.unique_comcontent.buckets;
    // 将这里下边的所有json中的key取出来组成一个数组
    keys = hits.map(hit => hit.key);
    this.ywNamescomcontent = keys
    console.log(keys)


    // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 事故预案推荐 namedetail


// 发送查询请求
    response = await axios.post(
      'http://43.136.220.136:9002/sqlgen/_search',
      {
        "size": 0,
        "aggs": {
          "unique_namedetail": {
            "terms": {
              "field": "namedetail.keyword",
              "size": 40000
            }
          }
        }
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Basic ' + btoa('admin:1992A1573')
        }
      }
    );
    console.log(response)
    // 处理响应数据
    hits = response.data.aggregations.unique_namedetail.buckets;
    // 将这里下边的所有json中的key取出来组成一个数组
    keys = hits.map(hit => hit.key);
    this.ywNamesnamedetail = keys
    console.log(keys)

    // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    // ---------------------------预案----------------------------------------


// 发送查询请求
    response = await axios.post(
      'http://43.136.220.136:9002/sqlgen/_search',
      {
        "size": 0,
        "aggs": {
          "unique_comps": {
            "terms": {
              "field": "comps.keyword",
              "size": 40000
            }
          }
        }
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Basic ' + btoa('admin:1992A1573')
        }
      }
    );
    console.log(response)
    // 处理响应数据
    hits = response.data.aggregations.unique_comps.buckets;
    // 将这里下边的所有json中的key取出来组成一个数组
    keys = hits.map(hit => hit.key);
    this.ywNamescomps = keys
    console.log(keys)


// 发送查询请求
    response = await axios.post(
      'http://43.136.220.136:9002/sqlgen/_search',
      {
        "size": 0,
        "aggs": {
          "unique_namedetail": {
            "terms": {
              "field": "namedetail.keyword",
              "size": 40000
            }
          }
        }
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Basic ' + btoa('admin:1992A1573')
        }
      }
    );
    console.log(response)
    // 处理响应数据
    hits = response.data.aggregations.unique_namedetail.buckets;
    // 将这里下边的所有json中的key取出来组成一个数组
    keys = hits.map(hit => hit.key);
    this.ywNamesnamedetail = keys
    console.log(keys)


// 发送查询请求
    response = await axios.post(
      'http://43.136.220.136:9002/sqlgen/_search',
      {
        "size": 0,
        "aggs": {
          "unique_codename": {
            "terms": {
              "field": "codename.keyword",
              "size": 40000
            }
          }
        }
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Basic ' + btoa('admin:1992A1573')
        }
      }
    );
    console.log(response)
    // 处理响应数据
    hits = response.data.aggregations.unique_codename.buckets;
    // 将这里下边的所有json中的key取出来组成一个数组
    keys = hits.map(hit => hit.key);
    this.ywNamescodename = keys
    console.log(keys)


// 发送查询请求
    response = await axios.post(
      'http://43.136.220.136:9002/sqlgen/_search',
      {
        "size": 0,
        "aggs": {
          "unique_codevalue": {
            "terms": {
              "field": "codevalue",
              "size": 40000
            }
          }
        }
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Basic ' + btoa('admin:1992A1573')
        }
      }
    );
    console.log(response)
    // 处理响应数据
    hits = response.data.aggregations.unique_codevalue.buckets;
    // 将这里下边的所有json中的key取出来组成一个数组
    keys = hits.map(hit => hit.key);
    this.ywNamescodevalue = keys
    console.log(keys)


    // -------------------------第二个参数-----------------------------------------------

    // 发送查询请求
    const response2 = await axios.post(
      'http://43.136.220.136:9002/sqlgen/_search',
      {
        "size": 0,
        "aggs": {
          "unique_operatemission": {
            "terms": {
              "field": "operatemission.keyword",
              "size": 40000
            }
          }
        }
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Basic ' + btoa('admin:1992A1573')
        }
      }
    );
    console.log(response2)
    // 处理响应数据
    const hits2 = response2.data.aggregations.unique_operatemission.buckets;
    // 将这里下边的所有json中的key取出来组成一个数组
    const keys2 = hits2.map(hit => hit.key);
    this.ywNames2 = keys2
    console.log(keys2)


  }

};
</script>
